package com.dm.cloud.utils.mq.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class RabbitPublishUtils implements RabbitTemplate.ConfirmCallback {

    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
    private static RabbitTemplate rabbitTemplate;

    /**     * 构造方法注入rabbitTemplate     */
    @Autowired
    public RabbitPublishUtils(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        //rabbitTemplate如果为单例的话，那回调就是最后confirm内容
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 回调
     **/
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info(" 回调id:" + correlationData + "消息成功消费");
        } else {
            log.info(" 回调id:" + correlationData + "消息消费失败:" + cause);
        }
    }

    /**
     * Direct
     * @param rabbitMQExchanges
     * @param rabbitMQRoutingKeys
     * @param content
     */
    public static void sendDirectMessage(RabbitMQExchanges rabbitMQExchanges,RabbitMQRoutingKeys rabbitMQRoutingKeys,Object content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(rabbitMQExchanges.getExchange(), rabbitMQRoutingKeys.getRoutingKey(), content, correlationId);
    }

    /**
     * Topic
     * @param routingKey
     * @param content
     */
    public static void sendTopicMessage(RabbitMQExchanges rabbitMQExchanges,String routingKey,Object content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());

        if(Strings.isBlank(routingKey)){
            log.error(" the exchange which type is 'topic' need a routingKey that cannot be blank ! ");
            return;
        }

        rabbitTemplate.convertAndSend(rabbitMQExchanges.getExchange(), routingKey, content, correlationId);

    }

    /**
     * Fanout 广播
     * @param content
     */
    public static void sendFanoutMessage(RabbitMQExchanges rabbitMQExchanges,Object content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(rabbitMQExchanges.getExchange(), "",content, correlationId);
    }
}